import {createStore} from 'vuex'
import request from '@/utils/request'

// 获取userInfo
let userInfo = localStorage.getItem('userInfo')
try{
    userInfo = JSON.parse(userInfo) || {}
}catch(error){
    userInfo ={}
}

const store= createStore({
    state(){
        return {
            userInfo,
        }
    },
    getters:{
        //是否登录
        isLogin(state){
            return !!state.userInfo.userId
        }
    },
    mutations:{
        login(state,payload){
            state.userInfo = payload
            localStorage.setItem('userInfo',JSON.stringify(payload))
        },
        logout(state,payload){
            state.userInfo ={}
            localStorage.removeItem('userInfo')
        },
    },
    actions:{
        async login(context,payload){
            console.log(payload)
            const { data }= await request.post('/user/login',{
                username:payload.username,
                password:payload.password
            })
 
            // 异步请求数据回来后，修改state（触发mutation）
            context.commit('login',data.data)

            return data
        }
    }
})

export default store